<script setup lang="tsx">
import { ElDialog } from 'element-plus'
import { Table, TableColumn } from '@/components/Table'
import { Icon } from '@/components/Icon'
import { BaseButton } from '@/components/Button'
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { ElMessage, ElUpload } from 'element-plus'

import { ref, reactive, computed } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { cloneDeep } from 'lodash-es'
import { SaveLevelImgApi } from '@/api/user'

import { uploadFile } from '@/api/upload'

const editVisible = ref(false)
//Table

const columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index'
  },

  {
    field: 'interestsName',
    label: '权益名称'
  },
  {
    field: 'logoUrl',
    label: '图片',
    slots: {
      default: ({ row }) => {
        return <img src={row.logoUrl} style={'width: 70px;'}></img>
      }
    }
  },
  {
    field: 'action',
    label: '操作',
    width: 130,
    fixed: 'right',
    slots: {
      default: ({ row }) => {
        return (
          <BaseButton class="!ml-0" type="primary" size="small" onClick={() => onOpenDialog(row)}>
            {{
              icon: () => <Icon size={20} icon="carbon:edit" />,
              default: () => '编辑'
            }}
          </BaseButton>
        )
      }
    }
  }
])
const { formRegister, formMethods } = useForm()
const { getFormData, setValues, getElFormExpose } = formMethods
const { required } = useValidator()

const disabled = ref(false)
const uploadImage = ref(false)
// 上传前校验文件
const beforeUpload = (rawFile) => {
  if (rawFile.size > 20 * 1024 * 1024) {
    ElMessage.error('图片过大,请重新选择!')
    return false
  }
  return true
}

const schema = computed<FormSchema[]>(() => [
  {
    field: 'interestsName',
    label: '权益名称',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'logoUrl',
    label: '图片',
    component: 'Input',
    formItemProps: {
      slots: {
        default: (formData) => {
          const httpRequest = async (options) => {
            uploadImage.value = true
            const formDataTemp = new FormData()
            formDataTemp.append('file', options.file)
            const { data } = await uploadFile(formDataTemp)
            formData.logoUrl = data[0].fileUrl
            uploadImage.value = false
          }

          const onRemoveFile = () => {
            formData.logoUrl = ''
          }
          return formData.logoUrl ? (
            <div class="w-[200px] h-[200px] overflow-hidden relative border-[1px] border-dashed border-[#ccc] border-rd-[6px]">
              <img class="w-[100%] absolute top-[50%] translate-y-[-50%]" src={formData.imageUrl} />
              <div
                class="w-[100%] h-[100%] absolute top-0 left-0 inline-flex justify-center items-center bg-[#000] opacity-1 hover-opacity-[0.5]"
                onClick={onRemoveFile}
              >
                <Icon
                  class="!color-[#fff] cursor-pointer"
                  icon="material-symbols:delete-outline"
                  size={30}
                />
              </div>
            </div>
          ) : (
            <ElUpload
              action="#"
              limit={1}
              accept="image/*"
              autoUpload={true}
              showFileList={false}
              disabled={uploadImage.value}
              httpRequest={httpRequest}
              beforeUpload={beforeUpload}
            >
              {{
                default: () => (
                  <Icon
                    icon={uploadImage.value ? 'line-md:uploading-loop' : 'mingcute:add-fill'}
                    size={40}
                  />
                ),
                tip: () => <div class="color-[#f59e0b]">文件大小不能超过20M</div>
              }}
            </ElUpload>
          )
        }
      },
      rules: [required('请上传图片')]
    }
  }
])
const onOpenDialog = (row) => {
  editVisible.value = true
  setValues(cloneDeep(row))
}
// 立即提交
const onFormSubmit = async () => {
  const elFormExpose = await getElFormExpose()
  elFormExpose?.validate(async (isValid) => {
    if (!isValid) {
      ElMessage.warning('请填写完整信息')
      return
    } else {
      disabled.value = true
      const formData = await getFormData()
      SaveLevelImgApi({ ...formData })
        .then(() => {
          visible.value = false
          ElMessage.success('操作成功！')
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          disabled.value = false
        })
    }
  })
}
// 重置
const onReset = async () => {
  const elFormExpose = await getElFormExpose()
  elFormExpose?.resetFields()
}
const visible = ref()
const levelInterestsDictionaryList = ref()
const openDialog = (row: any) => {
  visible.value = true
  levelInterestsDictionaryList.value = row.levelInterestsDictionaryList
}
defineExpose({
  openDialog
})
</script>

<template>
  <ElDialog title="权益记录" v-model="visible">
    <Table
      :columns="columns"
      :data="levelInterestsDictionaryList"
      row-key="id"
      sortable
      headerAlign="center"
      align="center"
    />
    <!-- 新增提示-弹窗 -->
    <ElDialog v-model="editVisible" title="编辑">
      <Form
        class="w-[500px] ml-[auto] mr-[auto]"
        labelPosition="top"
        :schema="schema"
        :isCol="false"
        @register="formRegister"
      />
      <template #footer>
        <div class="text-center mb-[16px]">
          <BaseButton @click="onReset">重置</BaseButton>
          <BaseButton type="primary" :disabled="disabled" debounce @click="onFormSubmit"
            >立即提交</BaseButton
          >
        </div>
      </template>
    </ElDialog>
  </ElDialog>
</template>
